package com.example.easynote;

import java.io.FileNotFoundException;
import java.io.IOException;

import java.io.File;

import java.util.ArrayList;
import java.util.Collections;



import org.json.JSONException;
import org.json.JSONObject;



import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;


import BUS.NotesBUS;
import BUS.paintBUS;
import BUS.picturesBUS;
import DAO.NotesDAO;
import DAO.paintDAO;
import DAO.picturesDAO;
import DTO.paintDTO;
import DTO.picturesDTO;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

import android.net.Uri;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;

import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SdCardPath")
public class EasyNoteMainActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	TabHost tabhost;
	Button btnAddnote;
	Button btnSearch;
	Button btnSelectDelete;
	Button btnManagerImage;
	Button btnRefresh;
	
	private static final int RESULT_CREATE = 100;
	private static final int RESULT_EDIT = 200;
	ListView listAll;

	private Cursor mNotesCursor;

	private ArrayList<String> listPic = new ArrayList<String>();

	private ArrayList<String> listPaint = new ArrayList<String>();

	NotesBUS noteBUS;

	@SuppressLint("ResourceAsColor")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_easy_note_main);

		tabhost = (TabHost) findViewById(R.id.tabhost);
		tabhost.setup();

		TabHost.TabSpec tabspec;

		tabspec = tabhost.newTabSpec("screen1");
		tabspec.setContent(R.id.tab1);
		tabspec.setIndicator("Tất cả ghi chú", null);

		tabhost.addTab(tabspec);

		tabspec = tabhost.newTabSpec("screen3");
		tabspec.setContent(R.id.tab3);
		tabspec.setIndicator("Ghi chú còn lại", null);
		tabhost.addTab(tabspec);

		tabhost.setCurrentTab(0);

		btnAddnote = (Button) findViewById(R.id.btnAddNote);
		btnSearch = (Button) findViewById(R.id.btnSearch);
		btnSelectDelete = (Button) findViewById(R.id.btnSelectDelete);
		btnManagerImage = (Button)findViewById(R.id.btnManagerImage);
		btnRefresh = (Button)findViewById(R.id.btnRefresh);
		
		btnAddnote.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		btnSelectDelete.setOnClickListener(this);
		btnManagerImage.setOnClickListener(this);
		btnRefresh.setOnClickListener(this);
		
		listAll = (ListView) findViewById(R.id.listAll);
		listAll.setOnItemClickListener(this);

		NotesDAO.open(this);
		picturesDAO.open(this);
		paintDAO.open(this);
		fillData();
		// link facebook

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.easy_note_main, menu);
		return true;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.btnManagerImage:
				startActivity(new Intent(this,MainActivity.class));
				break;
			case R.id.btnSelectDelete:
				CheckBox cb;
				final ArrayList<Integer> arrDelete = new ArrayList<Integer>();
				for (int x = 0; x < listAll.getChildCount(); x++) {
					cb = (CheckBox) listAll.getChildAt(x).findViewById(
							R.id.cbDelete);
					if (cb.isChecked()) {
						arrDelete.add(x);
					}
				}

				final Cursor c = mNotesCursor;
				AlertDialog alertDialog1 = new AlertDialog.Builder(
						EasyNoteMainActivity.this).create();
				// �?ặt tiêu đ�? cho Dialog
				alertDialog1.setTitle("Delete Dialog");
				// �?ặt Thông điệp dialog
				alertDialog1.setMessage("Bạn có muốn xóa ghi chú đã chọn");
				// thiết lập icon cho dialog
				alertDialog1.setIcon(R.drawable.ic_action_remove);
				// thiết lập button YES
				alertDialog1.setButton(DialogInterface.BUTTON_POSITIVE, "YES",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								for (int i = 0; i < arrDelete.size(); i++) {
									c.moveToPosition(arrDelete.get(i));
									//delete album anh
									File delete = new File(c.getString(c
											.getColumnIndexOrThrow(NotesDAO.KEY_URLFOLDER)));
									deleteFolder(delete);
									
									NotesBUS.deleteNote(c.getLong(c
											.getColumnIndexOrThrow(NotesDAO.KEY_ROWID)));
								}
								arrDelete.clear();
								fillData();
							}
						});
				// thiết lập button NO
				alertDialog1.setButton(DialogInterface.BUTTON_NEGATIVE, "NO",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								// ...
							}
						});
				// Showing Alert Message
				alertDialog1.show();
				break;
			case R.id.btnAddNote:
			{
				Intent newNote = new Intent(this, CreateNote.class);
				startActivityForResult(newNote, RESULT_CREATE);
			}
			break;
			case R.id.btnRefresh:
				fillData();
				break;
			case R.id.btnSearch:
			{
				EditText editSearch = (EditText) findViewById(R.id.editSearch);
				String search = editSearch.getText().toString();
				Log.i(search, search);
				int temp = search.compareTo("");
				if (temp == 0)
					fillData();
				else {
					Cursor result = NotesBUS.getNote(search);
					startManagingCursor(result);
					// Create an array to specify the fields we want to display
					// in
					// the list
					// (only TITLE)
					String[] from = new String[] { NotesDAO.KEY_TITLE };
					// and an array of the fields we want to bind those fields
					// to
					// (in this
					// case just text1)
					int[] to = new int[] { R.id.txtNoteName };
					listAll.setAdapter(new CustomAdapter(this,
							R.layout.notesingle, result, from, to));
					mNotesCursor = result;
				}
			}
			/*
			 * switch (arg0.getId()) { case R.id.btnAddNote: Intent newNote =
			 * new Intent(this, CreateNote.class);
			 * startActivityForResult(newNote, RESULT_CREATE); break; case
			 * R.id.btnSearch: Intent Search = new Intent(this, Search.class);
			 * startActivity(Search); break; }
			 */
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		try {
			Bundle extras = data.getExtras();
			Long rowId = extras.getLong(NotesDAO.KEY_ROWID);
			String editTitle = extras.getString(NotesDAO.KEY_TITLE);
			String editBody = extras.getString(NotesDAO.KEY_BODY);
			String editDate = extras.getString(NotesDAO.KEY_DATE);
			String urlFolder = extras.getString(NotesDAO.KEY_URLFOLDER);
			listPic = extras.getStringArrayList("ListPic");
			listPaint = extras.getStringArrayList("ListPaint");
			
			// use requestCode to find out who is talking to us
			switch (requestCode) {
			case RESULT_EDIT:

				if (rowId != null) {
					//sua ten folder
					File file1 = new File(urlFolder);
					urlFolder = Environment.getExternalStorageDirectory().toString()
							+ "/EasyNotes/" + Long.toString(rowId)+ "." + editTitle;
					File file2 = new File(urlFolder);
					file1.renameTo(file2);
					
					
					NotesBUS.updateNote(rowId, editTitle, editDate, editBody,urlFolder);
					
					for (int i = 0; i < listPic.size(); i++) {
						String temp = listPic.get(i);
						ArrayList<picturesDTO> listPicOfNote = picturesBUS
								.getAllPicfromNote(rowId);
						picturesBUS.createPictures((int)(rowId*100 + listPicOfNote.size()), rowId, temp);
						Log.i("id + rowID + urlPic",
								Integer.toString(i) + Long.toString(rowId)
										+ temp);
					}
					
					for (int i = 0; i < listPaint.size(); i++) {
						String temp = listPaint.get(i);
						ArrayList<paintDTO> listPaintOfNote = paintBUS
								.getAllPaintfromNote(rowId);
						//if (i >= listPaintOfNote.size()) {
							paintBUS.createpaint((int)(rowId*100 + listPaintOfNote.size()), rowId, temp);
							
						//}
						//else paintBUS.updatePaint((int)(rowId*100 + i),rowId,temp);
						Log.i("id + rowID + urlPaint",
								Integer.toString(i) + Long.toString(rowId)+ temp);
					}
				}
				break;
			case RESULT_CREATE:
				if (resultCode == RESULT_OK) { // thay đổi
					
					long id = NotesBUS.createNotes(editTitle, editDate, editBody,urlFolder);
					Log.i("ID RETURN", Long.toString(id));
					
					for (int i = 0; i < listPic.size(); i++) {
						String temp = listPic.get(i);
						picturesBUS.createPictures((int)(id*100 + i),id,temp);
						Log.i("id + rowID + urlPic",
								Integer.toString(i) + Long.toString(id)
										+ temp);
					}
					for(int i = 0 ;i<listPaint.size();i++)
					{
						String temp = listPaint.get(i);
						paintBUS.createpaint((int)(id*100 + i),id,temp);
						Log.i("id + rowID + urlPic",
								Integer.toString(i) + Long.toString(rowId)
										+ " " +temp);
					}
					//sua ten folder
					File file1 = new File(urlFolder);
					urlFolder = Environment.getExternalStorageDirectory().toString()
							+ "/EasyNotes/" + Long.toString(id)+ "." + editTitle;
					File file2 = new File(urlFolder);
					file1.renameTo(file2);
					
					NotesBUS.updateNote(id, editTitle, editDate, editBody,urlFolder);
					
					Log.i("TieuDe", editTitle);
					Log.i("NoiDung", editBody);
					Log.i("ThoiGian", editDate);
				}
				break;
			}
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), "error", Toast.LENGTH_LONG)
					.show();
		} finally {
			fillData();
		}
	}

	// Ghi vào cơ sở dữ liệu
	@SuppressWarnings("deprecation")
	private void fillData() {
		// Lấy tất các dòng từ cơ sở dữ liệu và tạo danh sách item
		mNotesCursor = NotesBUS.fetchAllNotes();
		startManagingCursor(mNotesCursor);
		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		String[] from = new String[] { NotesDAO.KEY_TITLE,NotesDAO.KEY_DATE };
		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to = new int[] { R.id.txtNoteName,R.id.txtDateTime };

		listAll.setAdapter(new CustomAdapter(this, R.layout.notesingle,
				mNotesCursor, from, to));
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Log.i("onItemClick", "Da vao toi day");

		Cursor c = mNotesCursor;
		c.moveToPosition(arg2);
		Intent i = new Intent(getApplicationContext(), CreateNote.class);
		i.putExtra(NotesDAO.KEY_ROWID, arg3);
		Log.i(NotesDAO.KEY_ROWID, Long.toString(arg3));
		
		i.putExtra("vitri",arg2);
		
		i.putExtra(NotesDAO.KEY_TITLE,
				c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_TITLE)));
		i.putExtra(NotesDAO.KEY_BODY,
				c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_BODY)));
		
		String url = c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_URLFOLDER));
		i.putExtra(NotesDAO.KEY_URLFOLDER,
				c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_URLFOLDER)));
		Log.i("KEY_URLFOLDER", url);
		
		ArrayList<picturesDTO> dto = picturesBUS.getAllPicfromNote(arg3); // id
																			// pictures
		ArrayList<paintDTO> paintdto = paintBUS.getAllPaintfromNote(arg3);
		ArrayList<String> listStr = new ArrayList<String>();
		ArrayList<String> listStrP = new ArrayList<String>();
		for (int j = 0; j < dto.size(); j++) {
			String temp = dto.get(j).getUrlPic();
			Log.i("PIC URL", temp);
			listStr.add(temp);
		}
		for (int j = 0; j < paintdto.size(); j++) {
			String temp1 = paintdto.get(j).getUrlPaint();
			Log.i("Paint URL", temp1);
			listStrP.add(temp1);
		}
		i.putExtra("ListPic", listStr);
		i.putExtra("ListPaint", listStrP);
		startActivityForResult(i, RESULT_EDIT);
	}

	public class CustomAdapter extends SimpleCursorAdapter {

		@SuppressWarnings("unused")
		private int mSelectedPosition;
		Cursor items;
		@SuppressWarnings("unused")
		private Context context;
		private int layout;

		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(layout, parent, false);

			return v;
		}
		
		@SuppressWarnings("deprecation")
		public CustomAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			this.context = context;
			this.layout = layout;
		}

		@Override
		public void bindView(View v, Context context, Cursor c) {

			int nameCol = c.getColumnIndex(NotesDAO.KEY_TITLE);
			String name = c.getString(nameCol);
			int dateCol = c.getColumnIndex(NotesDAO.KEY_DATE);
			String date = c.getString(dateCol);
			
			TextView name_text = (TextView) v.findViewById(R.id.txtNoteName);
			TextView date_text = (TextView) v.findViewById(R.id.txtDateTime);
			
			
			Button btnShare = (Button) v.findViewById(R.id.btnShare);
			Button btnDelete = (Button) v.findViewById(R.id.btnDelete);

			btnShare.setOnClickListener(mBuyButtonClickListener);
			btnDelete.setOnClickListener(mBuyButtonClickListener);

			if (name_text != null) {
				name_text.setText(name);
				date_text.setText(date);
			}
		}

		public void setSelectedPosition(int position) {
			mSelectedPosition = position;
			notifyDataSetChanged();
		}
	}

	private OnClickListener mBuyButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			final int position = listAll.getPositionForView(v);

			if (v.getId() == R.id.btnDelete) {
				if (position != AdapterView.INVALID_POSITION) {
					final Cursor c = mNotesCursor;
					c.moveToPosition(position);

					AlertDialog alertDialog1 = new AlertDialog.Builder(
							EasyNoteMainActivity.this).create();
					// �?ặt tiêu đ�? cho Dialog
					alertDialog1.setTitle("Delete Dialog");
					// �?ặt Thông điệp dialog
					alertDialog1.setMessage("Bạn có muốn xóa ghi chú này");
					// thiết lập icon cho dialog
					alertDialog1.setIcon(R.drawable.ic_action_remove);
					// thiết lập button YES
					alertDialog1.setButton(DialogInterface.BUTTON_POSITIVE,
							"YES", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									//delete album
									File delete = new File(c.getString(c
											.getColumnIndexOrThrow(NotesDAO.KEY_URLFOLDER)));
									deleteFolder(delete);
									
									NotesBUS.deleteNote(c.getLong(c
											.getColumnIndexOrThrow(NotesDAO.KEY_ROWID)));
									Toast.makeText(
											getApplicationContext(),
											"vừa xóa ghi chú "
													+ c.getString(c
															.getColumnIndexOrThrow(NotesDAO.KEY_TITLE)),
											Toast.LENGTH_LONG).show();
									fillData();
								}
							});
					// thiết lập button NO
					alertDialog1.setButton(DialogInterface.BUTTON_NEGATIVE,
							"NO", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									// ...
								}
							});
					// Showing Alert Message
					alertDialog1.show();
				}
			}
		}
	};

	// override lại vì tabhost tự focus khi nhập edittext
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		final EditText myInputField = (EditText) findViewById(R.id.editSearch);
		// this will happen on first key pressed on hard-keyboard only. Once
		// myInputField
		// gets the focus again, it will automatically receive further key
		// presses.
		if (!myInputField.hasFocus()) {
			myInputField.requestFocus();
			myInputField.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	
	// delete folder
	private void deleteFolder(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
            	deleteFolder(child);

        fileOrDirectory.delete();
    }
}
